import 'dart:math';

import 'package:flame/components.dart';
import 'package:flame/palette.dart';
import 'package:flutter/material.dart';

import 'DamageText.dart';

mixin Liveable on PositionComponent {
  var _text = TextComponent();
  var _pointRect = RectangleComponent();
  var _pointBgRect = RectangleComponent();
  double offsetY = 10; // 血条距构件顶部偏移量
  double _pointHeight = 6; // 血条宽度
  double _pointWidth = 20; // 血条高度
  late int _maxPoint; // 生命上限
  late int _currentPoint; // 当前生命值
  double get _progress => _currentPoint / _maxPoint; // 当前血条百分百
  var _damageText = DamageText();

  @override
  Future<void> onLoad() async {
    add(_pointBgRect);
    add(_pointRect);
    add(_text);
    add(_damageText);
    //debugMode = true;
    return super.onLoad();
  }

  void initPaint({
    required int point,
    double pointWidth = 16,
    double pointHeight = 6,
    double fontSize = 8,
    Color pointColor = Colors.red,
    Color bgColor = Colors.white,
    Color txtColor = Colors.white,
  }) {
    //print("_pointWidth=$_pointWidth  size.x=${size.x}");
    _maxPoint = point;
    _currentPoint = point;
    _pointWidth = pointWidth;
    _pointHeight = pointHeight;
    //血条背景
    _pointBgRect = RectangleComponent(
        position: Vector2((size.x - _pointWidth) / 2, -offsetY),
        size: Vector2(pointWidth, _pointHeight),
        paint: PaletteEntry(bgColor).paint());
    //血条
    _pointRect = RectangleComponent(
        position: Vector2((size.x - _pointWidth) / 2, -offsetY),
        size: Vector2(_pointWidth, _pointHeight),
        paint: PaletteEntry(pointColor).paint());
    //血条值
    _text = TextComponent(
        textRenderer:
            TextPaint(style: TextStyle(fontSize: fontSize, color: txtColor)));
    _text.text = "$_currentPoint/$_maxPoint";
    _text.position =
        Vector2((size.x - _text.width) / 2, -(offsetY + _text.height));
  }

  void changePoint(int point) {
    // 生成一个范围在 0 到 100 之间的随机整数
    int randomInt = Random().nextInt(101);
    if (randomInt < 50) {
      point *= 2;
      _damageText.addDamage(point);
    }
    if (point < 0) {
      _currentPoint = max(0, _currentPoint + point);
    } else {
      _currentPoint = min(_maxPoint, _currentPoint + point);
    }
    print("_currentPoint=$_currentPoint");
    if (_currentPoint == 0) {
      print("目标死亡");
    }
    //血量值 修改
    _text.text = "$_currentPoint/$_maxPoint";
    _text.position =
        Vector2((size.x - _text.width) / 2, -(offsetY + _text.height));
    //print("size.x=${size.x}  _text.width=${_text.width}");
    //血条 修改
    _pointRect.width = _pointWidth * _progress;
    print("_pointRect.width=${_pointRect.width}");
  }
}
